<?php
/**
 * (logic)
 */
namespace App\Logic\File\ProfitLT;

use App\Models\File\FileProfitLT;
use App\Util\RExcel;
use Illuminate\Support\Facades\DB;
class ParseFile
{
    /**
     * 解析 财务上传的月销售报表核算文件
     */
    public static function parse(){
        try{
            $parseFile = FileProfitLT::query()->where('status',1)->first();
            if(!$parseFile)die(0);
            DB::beginTransaction();
            if($parseFile->user_id != 1){
                $parseFile->status = 2;
                $parseFile->save();
                DB::commit();
            }else{
                $flag = self::_parseFiles($parseFile);
                if($flag){
                    $parseFile->status = 2;
                    $parseFile->save();
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 解析文件
     * @param $parseFile
     * @return bool
     */
    private static function _parseFiles($parseFile): bool
    {
        $file = self::_getParseFilePath($parseFile);
        if(!is_file($file))return false;
        ini_set('memory_limit', '2048M');
        set_time_limit(0);
        $lines = RExcel::importSheet($file);
        unset($lines[0]);
        return (self::$_class[$parseFile->file_type])::exeParse($lines,$parseFile->file_date);
    }

    //（临时类,创建临时数据）
    private static $_class = [
        1 => ParseSalesFile::class,            //销售明细费用
        2 => ParseReFeeFile::class,            //退货明细费用
        3 => ParseThFeeFile::class,            //第三方发货费
        4 => ParseServiceFeeFile::class,       //服务费
        5 => ParseCancelFile::class,           //取消明细
    ];

    /**
     * 获取文件路径
     * @param $parseFile
     * @return string
     */
    private static function _getParseFilePath($parseFile): string
    {
        $fileDir = FileProfitLT::fileDir(strtotime($parseFile->file_date));
        $fileName = FileProfitLT::fileName($parseFile->file_type,$parseFile->user_id,$parseFile->file_name);
        return public_uploads_path($fileDir).DIRECTORY_SEPARATOR.$fileName;
    }
}
